import React, { useEffect, useState } from "react";
import { Space, Table, Button, message, Input, Modal, Form } from "antd";
import type { TableProps } from "antd";
import http from "../../utils/http";
// 类型
interface DataType {
  key: React.Key;
  socoid: string;
  socoimage: string;
  socolv: string;
  socostate: string;
  socoadmin: string;
  sococity: string;
}

const Index: React.FC = () => {
  // 数据
   const [originalDatalist, setOriginalDatalist] = useState<DataType[]>([]);
  const [datalist, setDatalist] = useState([]);
   const [searchValue, setSearchValue] = useState("");
    const { Search } = Input;
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  // 分页
  const [pageCode, setPageCode] = useState(1);
  const [pageSize, setPageSize] = useState(500);
  const columns: TableProps<DataType>["columns"] = [
    {
      title: (
        <div>

          ID
        </div>
      ),
      align: "center",
      dataIndex: "socoid",
      key: "socoid",
    },
    {
      title: "医院图片",
      align: "center",
      dataIndex: "socoimage",
      key: "socoimage",
      render: (text, record) => {
        return (
          <img
            src={text}
            alt={record.socoimage}
            style={{ width: "80px", height: "80px" }}
          />
        );
      },
    },
    {
      title: "医院名称",
      align: "center",
      dataIndex: "socolv",
      key: "socolv",
    },
    {
      title: "医院类型",
      align: "center",
      dataIndex: "socostate",
      key: "socostate",
    },
    {
      title: "医院科室",
      align: "center",
      dataIndex: "socoadmin",
      key: "socoadmin",
    },
    {
      title: "医院地址",
      align: "center",
      dataIndex: "sococity",
      key: "sococity",
    },
    {
      title: "Action",
      align: "center",
      key: "socoid",
      render: (record) => (
        <Space size="middle">
          <Button type="primary" onClick={() => EditshowModal(record)}>
            编辑
          </Button>
          <Button type="primary" danger onClick={() => hanDel(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 渲染数据
  const FearchList = async () => {
    const res = await http.get("/nosocomium/list", {
      params: {
        pageCode,
        pageSize,
      },
    });
    const { code, data } = res.data;
    if (code === 20000) {
      setDatalist(data);
       setOriginalDatalist(data);
    }
  };
  useEffect(() => {
    FearchList();
  }, []);
  // 删除数据
  const hanDel = async (record: DataType) => {
    const res = await http.delete("/nosocomium/list", {
      params: {
        id: record.socoid,
      },
    });
    const { code } = res.data;
    if (code === 20000) {
      message.success("删除成功");
      FearchList();
    }
  };
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm();
  const [DialogState, setDialogState] = useState(true);
  // 编辑/添加
  const AddshowModal = () => {
    form.resetFields();
    setIsModalOpen(true);
    setDialogState(true);
  };
  const EditshowModal = (record: DataType) => {
    form.setFieldsValue(record);
    setIsModalOpen(true);
    setDialogState(false);
  };

  const handleOk = async () => {
    if (DialogState) {
      // 新增逻辑
      try {
        const values = form.getFieldsValue();
        const res = await http.put("/nosocomium/list", {
          name: values.nosocomium,
          lv: values.socolv,
          city: values.sococity,
          desc: values.socodescword,
          admin: values.socoadmin,
          state: values.socostate,
          image: values.socoimage,
        });
        const { code } = res.data;
        if (code === 20000) {
          message.success("新增成功");
          FearchList();
        } else {
          message.error("新增失败");
        }
      } catch (error) {
        console.error(error);
        message.error("新增失败");
      }
    } else {
      // 编辑逻辑
      try {
        const values = form.getFieldsValue();
        const res = await http.post(`/nosocomium/list`, {
          name: values.nosocomium,
          lv: values.socolv,
          city: values.sococity,
          desc: values.socodescword,
          admin: values.socoadmin,
          state: values.socostate,
          image: values.socoimage,
          id: values.socoid,
        });

        const { code } = res.data;
        if (code === 20000) {
          message.success("编辑成功");
          FearchList();
        } else {
          message.error("编辑失败");
        }
      } catch (error) {
        console.error(error);
        message.error("编辑失败");
      }
    }
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  // 查询
  const onSearch = (value: string) => {
    setSearchValue(value);
    if (!value) {
      setDatalist(originalDatalist);
    } else {
      const filteredData = originalDatalist.filter((item) =>
        Object.values(item).some((v) =>
          String(v).toLowerCase().includes(value.toLowerCase())
        )
      );
      setDatalist(filteredData);
    }
  };
  return (
    <div>
      <div>
        <Button
          type="primary"
          style={{ marginRight: "60px" }}
          onClick={() => AddshowModal()}
        >
          增加数据
        </Button>
        <Search
          placeholder="请输入搜索内容"
          allowClear
          enterButton="搜索"
          size="small"
          style={{ width: "300px" }}
          onSearch={onSearch}
        />
      </div>
      <Table<DataType>
        rowKey={"socoid"}
        rowSelection={{
          onChange(newSelectedRowKeys: React.Key[]) {
            console.log(newSelectedRowKeys);
            setSelectedRowKeys(newSelectedRowKeys);
          },
        }}
        columns={columns}
        dataSource={datalist}
      />
      {/* 添加编辑和增加弹框 */}
      <Modal
        title="Basic Modal"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={form} name="control-hooks" style={{ maxWidth: 600 }}>
          <Form.Item name="socoid" label="ID" rules={[{ required: true }]}>
            <Input disabled />
          </Form.Item>
          <Form.Item
            name="socoimage"
            label="医院图片"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="socolv"
            label="医院名称"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="socostate"
            label="医院类型"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="socoadmin"
            label="医院科室"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="sococity"
            label="医院地区"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Index;
